package com.lab.es.demo.message;

import com.alibaba.fastjson.JSON;
import com.lab.es.demo.dto.UpdateItemDTO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RocketMQMessageListener(topic = "${rocketmq.topic.testDelayTopic}", consumerGroup = "delayConsumerGroup")
public class ReceiveMessage implements RocketMQListener<UpdateItemDTO> {
    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

    @SneakyThrows
    @Override
    public void onMessage(UpdateItemDTO updateItemDTO) {
        UpdateRequest updateRequest = new UpdateRequest("tmall_items", updateItemDTO.getId());
        updateRequest.timeout("5s");

        updateRequest.doc(JSON.toJSONString(updateItemDTO), XContentType.JSON);
        UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println(updateResponse.status());
    }
}
